package com.upgrade.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {
    var iMyAidlInterface: IMyAidlInterface? = null
    private val conn: ServiceConnection = object : ServiceConnection {

        //绑定服务的时候
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {

            //远程服务
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service)
            toast("这里进来了")
        }

        //销毁服务的时候
        override fun onServiceDisconnected(name: ComponentName?) {
            //回收资源
            iMyAidlInterface = null
            toast("服务被销毁了")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bindService()
        btn_add.setOnClickListener {
            //调用远程服务
            val num1 = et1.text.toString()
            val num2 = et2.text.toString()
            iMyAidlInterface?.let {
                val addNum = it.addNum(num1.toInt(), num2.toInt())
                et_add.setText(addNum.toString())
            }
        }

    }

    //软件一启动就要绑定服务
    private fun bindService() {
        val intent = Intent()
        intent.component = ComponentName("com.upgrade.service", "com.upgrade.service.MyService")
        bindService(intent, conn, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(conn)
    }
}
